import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

// 从localStorage获取持久化数据的辅助函数
const getStorageState = () => {
    try {
        return {
            user: JSON.parse(localStorage.getItem('user')) || null,
            token: localStorage.getItem('token') || '',
            isAdmin: localStorage.getItem('isAdmin') === 'true'
        }
    } catch (e) {
        console.error('解析存储的用户数据失败:', e)
        return {
            user: null,
            token: '',
            isAdmin: false
        }
    }
}

export default new Vuex.Store({
    state: {
        ...getStorageState() // 初始化时从localStorage加载状态
    },
    mutations: {
        SET_USER(state, user) {
            state.user = user
            state.isAdmin = user && user.role === 'ADMIN'
            // 持久化存储用户信息
            localStorage.setItem('user', JSON.stringify(user))
            localStorage.setItem('isAdmin', String(state.isAdmin))
        },
        SET_TOKEN(state, token) {
            state.token = token
            localStorage.setItem('token', token)
        },
        CLEAR_USER(state) {
            state.user = null
            state.token = ''
            state.isAdmin = false
            // 清除所有存储的用户相关信息
            localStorage.removeItem('user')
            localStorage.removeItem('token')
            localStorage.removeItem('isAdmin')
            localStorage.removeItem('loginInfo')
        }
    },
    actions: {
        login({ commit }, { token, user }) {
            commit('SET_TOKEN', token)
            commit('SET_USER', user)
        },
        logout({ commit }) {
            commit('CLEAR_USER')
        },
        // 刷新页面时恢复状态的action
        restoreState({ commit }) {
            const state = getStorageState()
            if (state.user) {
                commit('SET_USER', state.user)
            }
            if (state.token) {
                commit('SET_TOKEN', state.token)
            }
        }
    },
    getters: {
        isAuthenticated: state => !!state.token && !!state.user,
        isAdmin: state => state.isAdmin,
        currentUser: state => state.user,
        token: state => state.token
    }
}) 